import FileSaver from 'file-saver'
import JSZip from 'jszip'

// 唯一id
function uuid() {
  var d = new Date().getTime()
  if (window.performance && typeof window.performance.now === 'function') {
    d += performance.now() //use high-precision timer if available
  }
  var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(
    /[xy]/g,
    function (c) {
      var r = (d + Math.random() * 16) % 16 | 0 // d是随机种子
      d = Math.floor(d / 16)
      return (c == 'x' ? r : (r & 0x3) | 0x8).toString(16)
    }
  )
  return uuid
}
// console.log( uuid() ) ;   //  826fe4be-631c-4a63-83e9-96a788e8a569
export const getUuid = uuid

//获取当前时间
export function getNowTime() {
  var date = new Date()
  //年 getFullYear()：四位数字返回年份
  var year = date.getFullYear() //getFullYear()代替getYear()
  //月 getMonth()：0 ~ 11
  var month = date.getMonth() + 1
  //日 getDate()：(1 ~ 31)
  var day = date.getDate()
  //时 getHours()：(0 ~ 23)
  var hour = date.getHours()
  //分 getMinutes()： (0 ~ 59)
  var minute = date.getMinutes()
  //秒 getSeconds()：(0 ~ 59)
  var second = date.getSeconds()

  var time =
    year +
    '-' +
    addZero(month) +
    '-' +
    addZero(day) +
    ' ' +
    addZero(hour) +
    ':' +
    addZero(minute) +
    ':' +
    addZero(second)
  return time
}
//小于10的拼接上0字符串
function addZero(s) {
  return s < 10 ? '0' + s : s
}

// 在目录树中找到指定节点
export function find_dirNode(datadir, mynodeKey) {
  for (let index = 0; index < datadir.length; index++) {
    var element = datadir[index]
    if (element.mynodeKey == mynodeKey) {
      return element
    }
    if (element.children && element.children.length != 0) {
      // 子文件夹
      var res = find_dirNode(element.children, mynodeKey)
      if (res) {
        return res
      }
    }
  }
}

// 生成一个url
export function getObjectURL(file) {
  var url = null
  if (window.createObjectURL != undefined) {
    url = window.createObjectURL(file)
  } else if (window.URL != undefined) {
    url = window.URL.createObjectURL(file)
  } else if (window.webkitURL != undefined) {
    url = window.webkitURL.createObjectURL(file)
  }
  return url
}

// file 转 base64
export function filetoBase64(file, fun_back) {
  let reader = new FileReader() //实例化文件读取对象

  reader.readAsDataURL(file) //将文件读取为 DataURL,也就是base64编码

  reader.onload = (e) => {
    //文件读取成功完成时触发

    let dataURL = e.target.result //获得文件读取成功后的DataURL,也就是base64编码

    // console.log(dataURL);
    if (fun_back) {
      fun_back(dataURL)
    }
    return dataURL
  }
}

export const funDownload = function (array, filename) {
  let zip = new JSZip()
  for (let index = 0; index < array.length; index++) {
    const element = array[index]
    let blob = new Blob([element.data])
    zip.file(element.name, blob)
  }

  zip
    .generateAsync({
      type: 'blob'
    })
    .then((content) => {
      FileSaver.saveAs(content, filename)
    })

}
